﻿namespace Offy.Itdev.BuyIn.Intranet.Core.Impl
{
    using System;
    using System.Reflection;
    using System.Collections.Generic;
    using Repositories;
    using Contracts;
    using Constant;
    using DTO;
    using Microsoft.SharePoint;

    public class ProductDAL : BaseDao<ProductDTO>, IProductDAL
    {
        public ProductDAL() : base(SPContext.Current.Web, Lists.Product) { }

        public ProductDAL(SPWeb web) : base(web, Lists.Product) { }

        public IList<ProductDTO> GetList()
        {
            var query = "<Where><IsNotNull><FieldRef Name='ID'/></IsNotNull></Where>";
            var list1 = base.GetList(query, 1, 10, string.Empty);
            //var list2 = base.GetList(query, 2, 2, string.Empty);
            //var list3 = base.GetList(query, 3, 2, string.Empty);
            //var list4 = base.GetList(query, 4, 2, string.Empty);

            return list1;
        }

        public ProductDTO Get(int id)
        {
            return this.GetById(id);
        }

        public int AddProduct(ProductDTO product)
        {
            return Add(product);
        }

        protected override ProductDTO MapDTO(SPListItem item)
        {
            var entity = new ProductDTO();
            entity.ID = item.ID;
            entity.Title = item.Title;

            var lookupField = new SPFieldLookupValue(item["Category"] as string);

            entity.Category = new LookupDTO() { ID = lookupField.LookupId, Title = lookupField .LookupValue };

            var lookupFields = new SPFieldLookupValueCollection(item["CategoryList"] as string);
            foreach (var field in lookupFields)
            {
                entity.CategoryList.Add(new LookupDTO() { ID = field.LookupId, Title = field.LookupValue });
            }
            
            return entity;
        }
    }
}
